import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'version_logic.dart';
import 'version_state.dart';

/// 版本管理页面 - Version Management Page
/// 显示 Prompt 的版本历史，支持版本对比、回滚等操作
class VersionView extends StatelessWidget {
  const VersionView({super.key});

  @override
  Widget build(BuildContext context) {
    final logic = Get.find<VersionLogic>();
    final state = Get.find<VersionLogic>().state;

    return Scaffold(
      backgroundColor: Colors.grey[50],
      appBar: _buildAppBar(logic, state),
      body: Column(
        children: [
          // 搜索栏和统计信息 - Search Bar and Statistics
          _buildSearchSection(logic, state),
          
          // 版本列表 - Version List
          Expanded(
            child: _buildVersionList(logic, state),
          ),
        ],
      ),
      
      // 浮动操作按钮 - Floating Action Button
      floatingActionButton: _buildFloatingActionButton(logic, state),
    );
  }

  /// 构建应用栏 - Build App Bar
  PreferredSizeWidget _buildAppBar(VersionLogic logic, VersionState state) {
    return AppBar(
      title: Text(
        '版本历史 (${state.filteredVersions.length})',
        style: const TextStyle(
          fontSize: 18,
          fontWeight: FontWeight.w600,
        ),
      ),
      backgroundColor: Colors.white,
      foregroundColor: Colors.black87,
      elevation: 0,
      actions: [
        // 搜索按钮 - Search Button
        IconButton(
          icon: Icon(
            state.isSearchVisible ? Icons.search_off : Icons.search,
            color: Colors.grey[700],
          ),
          onPressed: logic.toggleSearch,
          tooltip: state.isSearchVisible ? '关闭搜索' : '搜索版本',
        ),
        
        // 排序按钮 - Sort Button
        PopupMenuButton<String>(
          icon: Icon(Icons.sort, color: Colors.grey[700]),
          tooltip: '排序方式',
          onSelected: logic.changeSortOrder,
          itemBuilder: (context) => [
            const PopupMenuItem(
              value: 'time_desc',
              child: Row(
                children: [
                  Icon(Icons.access_time, size: 18),
                  SizedBox(width: 8),
                  Text('按时间降序'),
                ],
              ),
            ),
            const PopupMenuItem(
              value: 'time_asc',
              child: Row(
                children: [
                  Icon(Icons.access_time, size: 18),
                  SizedBox(width: 8),
                  Text('按时间升序'),
                ],
              ),
            ),
            const PopupMenuItem(
              value: 'version_desc',
              child: Row(
                children: [
                  Icon(Icons.tag, size: 18),
                  SizedBox(width: 8),
                  Text('按版本号降序'),
                ],
              ),
            ),
            const PopupMenuItem(
              value: 'version_asc',
              child: Row(
                children: [
                  Icon(Icons.tag, size: 18),
                  SizedBox(width: 8),
                  Text('按版本号升序'),
                ],
              ),
            ),
          ],
        ),
        
        // 更多操作 - More Actions
        PopupMenuButton<String>(
          icon: Icon(Icons.more_vert, color: Colors.grey[700]),
          tooltip: '更多操作',
          onSelected: (value) {
            switch (value) {
              case 'export_all':
                logic.exportAllVersions();
                break;
              case 'clear_old':
                logic.clearOldVersions();
                break;
            }
          },
          itemBuilder: (context) => [
            const PopupMenuItem(
              value: 'export_all',
              child: Row(
                children: [
                  Icon(Icons.download, size: 18),
                  SizedBox(width: 8),
                  Text('导出所有版本'),
                ],
              ),
            ),
            const PopupMenuItem(
              value: 'clear_old',
              child: Row(
                children: [
                  Icon(Icons.delete_sweep, size: 18),
                  SizedBox(width: 8),
                  Text('清理旧版本'),
                ],
              ),
            ),
          ],
        ),
      ],
    );
  }

  /// 构建搜索区域 - Build Search Section
  Widget _buildSearchSection(VersionLogic logic, VersionState state) {
    return AnimatedContainer(
      duration: const Duration(milliseconds: 300),
      height: state.isSearchVisible ? 120 : 60,
      padding: const EdgeInsets.all(16),
      decoration: BoxDecoration(
        color: Colors.white,
        boxShadow: [
          BoxShadow(
            color: Colors.grey.withOpacity(0.1),
            blurRadius: 4,
            offset: const Offset(0, 2),
          ),
        ],
      ),
      child: Column(
        children: [
          // 版本统计信息 - Version Statistics
          Row(
            children: [
              _buildStatCard(
                '总版本数',
                '${state.versions.length}',
                Icons.history,
                Colors.blue,
              ),
              const SizedBox(width: 16),
              _buildStatCard(
                '今日版本',
                '${state.todayVersionCount}',
                Icons.today,
                Colors.green,
              ),
              const SizedBox(width: 16),
              _buildStatCard(
                '已选择',
                '${state.selectedVersions.length}',
                Icons.check_circle,
                Colors.orange,
              ),
            ],
          ),
          
          // 搜索框 - Search Box
          if (state.isSearchVisible) ...[
            const SizedBox(height: 12),
            TextField(
              controller: state.searchController,
              onChanged: logic.searchVersions,
              decoration: InputDecoration(
                hintText: '搜索版本内容、备注...',
                prefixIcon: const Icon(Icons.search, size: 20),
                suffixIcon: state.searchController.text.isNotEmpty
                    ? IconButton(
                        icon: const Icon(Icons.clear, size: 20),
                        onPressed: () {
                          state.searchController.clear();
                          logic.searchVersions('');
                        },
                      )
                    : null,
                border: OutlineInputBorder(
                  borderRadius: BorderRadius.circular(8),
                  borderSide: BorderSide(color: Colors.grey[300]!),
                ),
                focusedBorder: OutlineInputBorder(
                  borderRadius: BorderRadius.circular(8),
                  borderSide: const BorderSide(color: Colors.blue),
                ),
                contentPadding: const EdgeInsets.symmetric(
                  horizontal: 16,
                  vertical: 12,
                ),
              ),
            ),
          ],
        ],
      ),
    );
  }

  /// 构建统计卡片 - Build Statistics Card
  Widget _buildStatCard(String title, String value, IconData icon, Color color) {
    return Expanded(
      child: Container(
        padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8),
        decoration: BoxDecoration(
          color: color.withOpacity(0.1),
          borderRadius: BorderRadius.circular(8),
          border: Border.all(color: color.withOpacity(0.3)),
        ),
        child: Row(
          children: [
            Icon(icon, color: color, size: 16),
            const SizedBox(width: 8),
            Expanded(
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text(
                    title,
                    style: TextStyle(
                      fontSize: 11,
                      color: Colors.grey[600],
                    ),
                  ),
                  Text(
                    value,
                    style: TextStyle(
                      fontSize: 14,
                      fontWeight: FontWeight.w600,
                      color: color,
                    ),
                  ),
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }

  /// 构建版本列表 - Build Version List
  Widget _buildVersionList(VersionLogic logic, VersionState state) {
    return Builder(
      builder: (context) {
        if (state.isLoading) {
          return const Center(
            child: CircularProgressIndicator(),
          );
        }

        if (state.filteredVersions.isEmpty) {
          return _buildEmptyState();
        }

        return ListView.builder(
          padding: const EdgeInsets.all(16),
          itemCount: state.filteredVersions.length,
          itemBuilder: (context, index) {
            final version = state.filteredVersions[index];
          return _buildVersionItem(logic, state, version, index);
        },
      );
    });
  }

  /// 构建空状态 - Build Empty State
  Widget _buildEmptyState() {
    return Center(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Icon(
            Icons.history,
            size: 64,
            color: Colors.grey[400],
          ),
          const SizedBox(height: 16),
          Text(
            '暂无版本历史',
            style: TextStyle(
              fontSize: 16,
              color: Colors.grey[600],
            ),
          ),
          const SizedBox(height: 8),
          Text(
            '开始编辑 Prompt 后会自动创建版本',
            style: TextStyle(
              fontSize: 14,
              color: Colors.grey[500],
            ),
          ),
        ],
      ),
    );
  }

  /// 构建版本项 - Build Version Item
  Widget _buildVersionItem(
    VersionLogic logic,
    VersionState state,
    VersionInfo version,
    int index,
  ) {
    final isSelected = state.selectedVersions.contains(version.id);
    final isLatest = index == 0;

    return Container(
      margin: const EdgeInsets.only(bottom: 12),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(12),
        border: Border.all(
          color: isSelected ? Colors.blue : Colors.grey[200]!,
          width: isSelected ? 2 : 1,
        ),
        boxShadow: [
          BoxShadow(
            color: Colors.grey.withOpacity(0.1),
            blurRadius: 4,
            offset: const Offset(0, 2),
          ),
        ],
      ),
      child: InkWell(
        borderRadius: BorderRadius.circular(12),
        onTap: () => logic.toggleVersionSelection(version.id),
        onLongPress: () => logic.viewVersionDetail(version.id),
        child: Padding(
          padding: const EdgeInsets.all(16),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              // 版本头部信息 - Version Header
              Row(
                children: [
                  // 版本号和标签 - Version Number and Tags
                  Expanded(
                    child: Row(
                      children: [
                        Container(
                          padding: const EdgeInsets.symmetric(
                            horizontal: 8,
                            vertical: 4,
                          ),
                          decoration: BoxDecoration(
                            color: isLatest ? Colors.green : Colors.blue,
                            borderRadius: BorderRadius.circular(4),
                          ),
                          child: Text(
                            isLatest ? '最新' : 'v${version.version}',
                            style: const TextStyle(
                              color: Colors.white,
                              fontSize: 12,
                              fontWeight: FontWeight.w500,
                            ),
                          ),
                        ),
                        if (version.isAutoSave) ...[
                          const SizedBox(width: 8),
                          Container(
                            padding: const EdgeInsets.symmetric(
                              horizontal: 6,
                              vertical: 2,
                            ),
                            decoration: BoxDecoration(
                              color: Colors.orange[100],
                              borderRadius: BorderRadius.circular(3),
                            ),
                            child: Text(
                              '自动保存',
                              style: TextStyle(
                                color: Colors.orange[700],
                                fontSize: 10,
                              ),
                            ),
                          ),
                        ],
                      ],
                    ),
                  ),
                  
                  // 选择框 - Selection Checkbox
                  Checkbox(
                    value: isSelected,
                    onChanged: (value) => logic.toggleVersionSelection(version.id),
                    materialTapTargetSize: MaterialTapTargetSize.shrinkWrap,
                  ),
                ],
              ),
              
              const SizedBox(height: 12),
              
              // 版本信息 - Version Information
              Row(
                children: [
                  Expanded(
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Text(
                          logic.formatDateTime(version.createdAt),
                          style: TextStyle(
                            fontSize: 14,
                            color: Colors.grey[600],
                          ),
                        ),
                        const SizedBox(height: 4),
                        Text(
                          '${version.getContentLength()} 字符',
                          style: TextStyle(
                            fontSize: 12,
                            color: Colors.grey[500],
                          ),
                        ),
                      ],
                    ),
                  ),
                  
                  // 操作按钮 - Action Buttons
                  Row(
                    mainAxisSize: MainAxisSize.min,
                    children: [
                      IconButton(
                        icon: const Icon(Icons.visibility, size: 18),
                        onPressed: () => logic.viewVersionDetail(version.id),
                        tooltip: '查看详情',
                        constraints: const BoxConstraints(
                          minWidth: 32,
                          minHeight: 32,
                        ),
                      ),
                      if (!isLatest)
                        IconButton(
                          icon: const Icon(Icons.restore, size: 18),
                          onPressed: () => logic.restoreVersion(version.id),
                          tooltip: '恢复此版本',
                          constraints: const BoxConstraints(
                            minWidth: 32,
                            minHeight: 32,
                          ),
                        ),
                      PopupMenuButton<String>(
                        icon: const Icon(Icons.more_vert, size: 18),
                        tooltip: '更多操作',
                        onSelected: (value) {
                          switch (value) {
                            case 'export':
                              logic.exportVersion(version.id);
                              break;
                            case 'delete':
                              logic.deleteVersion(version.id);
                              break;
                            case 'duplicate':
                              logic.duplicateVersion(version.id);
                              break;
                          }
                        },
                        itemBuilder: (context) => [
                          const PopupMenuItem(
                            value: 'export',
                            child: Row(
                              children: [
                                Icon(Icons.download, size: 16),
                                SizedBox(width: 8),
                                Text('导出'),
                              ],
                            ),
                          ),
                          const PopupMenuItem(
                            value: 'duplicate',
                            child: Row(
                              children: [
                                Icon(Icons.copy, size: 16),
                                SizedBox(width: 8),
                                Text('复制'),
                              ],
                            ),
                          ),
                          if (!isLatest)
                            const PopupMenuItem(
                              value: 'delete',
                              child: Row(
                                children: [
                                  Icon(Icons.delete, size: 16, color: Colors.red),
                                  SizedBox(width: 8),
                                  Text('删除', style: TextStyle(color: Colors.red)),
                                ],
                              ),
                            ),
                        ],
                      ),
                    ],
                  ),
                ],
              ),
              
              // 版本备注 - Version Notes
              if (version.notes.isNotEmpty) ...[
                const SizedBox(height: 8),
                Container(
                  padding: const EdgeInsets.all(8),
                  decoration: BoxDecoration(
                    color: Colors.grey[50],
                    borderRadius: BorderRadius.circular(6),
                  ),
                  child: Text(
                    version.notes,
                    style: TextStyle(
                      fontSize: 13,
                      color: Colors.grey[700],
                    ),
                  ),
                ),
              ],
              
              // 内容预览 - Content Preview
              if (version.getContentPreview().isNotEmpty) ...[
                const SizedBox(height: 8),
                Text(
                  version.getContentPreview(),
                  style: TextStyle(
                    fontSize: 13,
                    color: Colors.grey[600],
                    height: 1.4,
                  ),
                  maxLines: 2,
                  overflow: TextOverflow.ellipsis,
                ),
              ],
            ],
          ),
        ),
      ),
    );
  }

  /// 构建浮动操作按钮 - Build Floating Action Button
  Widget? _buildFloatingActionButton(VersionLogic logic, VersionState state) {
    if (state.selectedVersions.length < 2) return null;

    return FloatingActionButton.extended(
      onPressed: logic.compareSelectedVersions,
      icon: const Icon(Icons.compare_arrows),
      label: Text('对比 (${state.selectedVersions.length})'),
      backgroundColor: Colors.blue,
    );
  }
}